package com.chzu.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.support.spring.annotation.ResponseJSONP;
import com.chzu.mapper.SysUserMapper;
import com.chzu.pojo.SysRole;
import com.chzu.pojo.SysUser;
import com.chzu.result.JsonResult;
import com.chzu.service.SysUserService;
import com.fasterxml.jackson.databind.annotation.JsonAppend;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @Author lz
 * @Version 1.0
 * @Company 滁州大健康与养老产业研究院
 * @ClassName MiniController
 * @Description 微信小程序登录接口
 * @Date 2022/01/28 10:12
 */
@RestController
@RequestMapping("/mini")
@Slf4j
@Api(tags = "微信小程序登录接口")
public class MiniController {

    @Value("${wx.appid}")
    private String appId;
    @Value("${wx.secret}")
    private String secret;
    @Resource
    private SysUserService userService;


    @ApiOperation(value = "微信小程序登录")
    @GetMapping("/login")
    public JsonResult<Object> miniLogin(String code) {
        if(code == null || "".equals(code)) {
            return JsonResult.fail("登录失败，请联系管理员");
        }
        String url = "https://api.weixin.qq.com/sns/jscode2session?" + "appid=" +
                appId +
                "&secret=" +
                secret +
                "&js_code=" +
                code +
                "&grant_type=authorization_code";
        // 创建client请求
        CloseableHttpClient client = HttpClientBuilder.create().build();
        // 构建get请求
        HttpGet get = new HttpGet(url);
        // 发送请求
        CloseableHttpResponse response = null;
        JsonResult<Object> objectJsonResult = null;
        try {
            response = client.execute(get);
            assert response != null;
            log.info("请求响应码：{}",response.getStatusLine().getStatusCode());
            String result = EntityUtils.toString(response.getEntity());
            log.info("请求相应结果：{}",result);
            JSONObject jsonObject = JSON.parseObject(result);
            String openid = jsonObject.getString("openid");
            log.info("小程序唯一标识：{}", openid);
            objectJsonResult = userService.miniLogin(openid);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return objectJsonResult;
    }


    /**
     * 根据openid更新用户信息
     * @param user 用户对象
     * @return
     */
    @ApiOperation(value = "更新用户信息")
    @PostMapping("/update/info")
    public JsonResult<Object> updateInfo(@RequestBody SysUser user) {
        return userService.updateInfo(user);
    }
}
